<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 17-1-3
 * Time: 下午3:37
 */

namespace common\repositories\outstock;


use common\entities\outstock\MyscrmOutStockStepEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;

class OutStockStepRepository extends BaseRepository
{
    /**
     * 创建流程步骤
     * @param MyscrmOutStockStepEntity $model
     * @return bool|string
     */
    public function create(MyscrmOutStockStepEntity $model)
    {
        if (empty($model->id)) {
            $model->id = StringHelper::uuid();
        }

        if ($model->save()) {
            return $model->id;
        }

        $errors = $model->getFirstErrors();

        return self::setAndReturn(__LINE__, implode(';', $errors));
    }

    /**
     * 获取最后的审批用户ID
     * @param $orderId
     * @return bool|string
     */
    public function getLatestSpStep($orderId)
    {
        return MyscrmOutStockStepEntity::find()
            ->where([
                'order_id' => $orderId,
                'action'   => 20, //审批
            ])
            ->orderBy('created_on DESC')
            ->one();
    }

    /**
     * 获取审批记录
     * @param $orderId
     * @return array|MyscrmOutStockStepEntity[]
     */
    public function getStepList($orderId)
    {
        return MyscrmOutStockStepEntity::find()
            ->where([
                'order_id' => $orderId,
                'action'   => [1, 10, 11, 20, 21],//动作：1发起，10打回，11撤回，20审批，21确认，22开通，23授权',
            ])
            ->orderBy('created_on DESC')
            ->all();

    }

    /**
     * 获取最后一次发起信息
     * @param $orderId
     * @return MyscrmOutStockStepEntity
     */
    public function getLatestFqStep($orderId)
    {
        return MyscrmOutStockStepEntity::find()
            ->where([
                'order_id' => $orderId,
                'action'   => 1, //发起
            ])
            ->orderBy('created_on DESC')
            ->one();
    }

    /**
     * 审批记录是否存在
     * @param $orderId
     * @return bool
     */
    public function hasStep($orderId)
    {
        return MyscrmOutStockStepEntity::find()
            ->where([
                'order_id' => $orderId,
                'action' => [1, 10, 11, 20, 21],//动作：1发起，10打回，11撤回，20审批，21确认，22开通，23授权',
            ])
            ->exists();
    }
}